const WebSocket = require('ws');
const http = require('http');
const url = require('url');
const querystring = require('querystring');


const server = http.createServer();
const wss = new WebSocket.Server({ server });

// 存储所有客户端连接的集合
const clients = new Set();


// function broadcast(message) {
//     // 向所有客户端广播消息
//     for (const client of clients) {
//         client.send(message);
//     }
// }

function startWebSocket(port,receive){
    wss.on('connection', (ws, req) => {
        const path = req.url;

        // 解析 URL 中的查询参数
        const parsedUrl = url.parse(req.url);
        const queryParams = querystring.parse(parsedUrl.query);

        // 获取 sid 的值
        const sid = queryParams.sid;

        let wsClient = {sid:sid,ws:ws};

        // 将新连接添加到集合中
        clients.add(wsClient);

        console.log(`websocket server was connected from ${path},all client size=${clients.size}`);
        // console.log(`WebSocket 连接已建立，当前连接数: ${clients.size}`);

        ws.on('message', (data, isBinary) => {
            let message = isBinary?data:data.toString();
            // debugger;
            var wsClient = getWsClientByWs(ws);
            // 处理收到的消息
            console.log(`receive message: ${message}`);
            receive(message,wsClient.sid);
            // // 广播消息给所有客户端
            // broadcast(message);
        });

        ws.on('close', () => {
            // 将关闭的连接从集合中移除
            // debugger;
            let wsClient = getWsClientByWs(ws);
            clients.delete(wsClient);
            console.log(`WebSocket closed，all client size: ${clients.size}`);
        });
    });
    server.listen(port, () => {
        console.log('WebSocket server start at ', port);
    });

}


// function startWebSocket(port,receive){
//     websocketWs = new WebSocket.Server({ port: port });
//     console.log("start websocket server at ",port);
//     websocketWs.on('connection', function (ws,req) {
//         const path = req.url;
//         console.log('websocket server start at ',path);
//         // websocketWs = ws;
//         sendMessage('system','ws server start success');
//         // websocketWs.send("ws start success");
//     });
//     websocketWs.on('message', function (data, isBinary) {
//         let message = isBinary?data:data.toString();
//         console.log('Message from client ', message);
//         receive(message);
//     });
//     // setInterval(function(){
//     //     exec_system_file('log',[],function(message){
//     //         message = message.trim()
//     //         if(message){
//     //             websocketWs.send(message.trim())
//     //         }
//     //     });
//     // },3000)
// }

function getWsClientByWs(ws){
    for (const client of clients) {
        if(ws == client.ws){
            return client;
        }
    }
    return null;
}

/**
 *
 * @param type （log,system,biz）
 * @param message 字符串或对象
 * @param sid
 */
function sendMessage(type,message,sid){
    let data = JSON.stringify({type:type,message:message})
    for (const client of clients) {
        if(!sid || client.sid == sid){
            client.ws.send(data);
        }
    }
}

function closeAll(){
    for (const client of clients) {
        client.ws.close();
    }
    // websocketWs.close();
}

function close(sid){
    for (const client of clients) {
        if (client.sid == sid) {
            client.ws.close();
            break;
        }
    }
    // websocketWs.close();
}

// 导出模块函数
module.exports = {
    startWebSocket,
    sendMessage,
    closeAll,
    close,
};
